<template>
  <el-table ref="multipleTableRef" :data="tableData" style="width: 100%" :row-key="rowKey" @selection-change="handleSelectionChange" @row-click="handleRowClick" :row-class-name="rowClassName">
    <el-table-column type="selection" :selectable="selectable" width="55" />
    <el-table-column prop="id" label="ID" width="80" />
    <el-table-column prop="name" label="姓名" />
    <el-table-column prop="age" label="年龄" width="100" />
  </el-table>
</template>

<script setup>
import { ref } from 'vue'

let tableData = ref([
  { id: 1, name: '张三', age: 18 },
  { id: 2, name: '李四', age: 25 },
  { id: 3, name: '王五', age: 30 },
  { id: 4, name: '王五', age: 30 },
  { id: 5, name: '王小六', age: 30 },
  { id: 6, name: '张小七', age: 30 },
  { id: 7, name: '李小八', age: 30 }
])
const multipleTableRef = ref(null)
const multipleSelection = ref([])
// 选中的行id数组
const selectedRowKeys = ref([])
// 指定唯一key
let rowKey = row => row.id
// sf单选多选
let isRadioCheck = ref('2')
// 点击行事件
const handleRowClick = row => {
  let key = rowKey(row)
  if (isRadioCheck.value === '1') {
    multipleTableRef.value.clearSelection()
    multipleTableRef.value.toggleRowSelection(row, undefined, false)
    selectedRowKeys.value = [key]
  } else {
    multipleTableRef.value.toggleRowSelection(row, undefined, false)
    let index = selectedRowKeys.value.indexOf(key)
    if (index === -1) {
      // 不存在，加入选中
      selectedRowKeys.value.push(key)
    } else {
      // 已选中，取消选中
      selectedRowKeys.value.splice(index, 1)
    }
  }
}
const handleSelectionChange = val => {
  if (val.length > 0) {
    multipleSelection.value = val
    console.log('测试数据打印多选', val)
  }
}
// 自定义行样式，选中行加背景色
const rowClassName = ({ row }) => {
  return selectedRowKeys.value.includes(rowKey(row)) ? 'row-selected' : ''
}
</script>

<style>
.row-selected {
  background-color: #f0f9eb !important;
}
</style>
